<?php
/**
 * 价值链内容管理页面
 */

require_once 'config/config.php';
require_once 'includes/db.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/installed.lock')) {
    header('Location: install.php');
    exit;
}

// 检查管理员登录
session_start();
if (!($_SESSION['admin_logged_in'] ?? false)) {
    header('Location: login.php');
    exit;
}

$message = '';
$messageType = '';

if ($_POST) {
    // CSRF令牌验证
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $message = '安全验证失败';
        $messageType = 'error';
    } else {
        try {
            $db = new Database();

            $data = [
                'page_title' => trim($_POST['page_title'] ?? ''),
                'page_description' => trim($_POST['page_description'] ?? ''),
                'file_name' => trim($_POST['file_name'] ?? ''),
                'file_description' => trim($_POST['file_description'] ?? ''),
                'file_size' => trim($_POST['file_size'] ?? '')
            ];

            // 验证输入
            if (empty($data['page_title'])) {
                $message = '请填写页面标题';
                $messageType = 'error';
            } elseif (empty($data['file_name'])) {
                $message = '请填写文件名称';
                $messageType = 'error';
            } else {
                $db->saveValueChainContent($data);
                $message = '保存成功！';
                $messageType = 'success';
            }
        } catch (Exception $e) {
            $message = '保存失败: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
}

// 获取现有内容
try {
    $db = new Database();
    $content = $db->getValueChainContent();
} catch (Exception $e) {
    $message = '加载数据失败: ' . $e->getMessage();
    $messageType = 'error';
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>价值链内容管理 - <?= SITE_NAME ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f7;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .header {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-left h1 {
            color: #333;
            font-size: 28px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-left p {
            color: #666;
            font-size: 14px;
        }

        .header-right {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .admin-badge {
            background: #007AFF;
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
        }

        .btn {
            padding: 10px 24px;
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);
            background: #0056CC;
        }

        .btn-danger {
            background: #FF3B30;
            box-shadow: 0 2px 8px rgba(255, 59, 48, 0.2);
        }

        .btn-danger:hover {
            background: #D70015;
            box-shadow: 0 4px 16px rgba(255, 59, 48, 0.3);
        }

        .btn-secondary {
            background: #8E8E93;
            box-shadow: 0 2px 8px rgba(142, 142, 147, 0.2);
        }

        .btn-secondary:hover {
            background: #6E6E73;
            box-shadow: 0 4px 16px rgba(142, 142, 147, 0.3);
        }

        .form-container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .form-title {
            font-size: 24px;
            font-weight: 600;
            color: #1d1d1f;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .form-group {
            margin-bottom: 24px;
        }

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #1d1d1f;
            margin-bottom: 8px;
        }

        .form-label.required::after {
            content: ' *';
            color: #FF3B30;
        }

        .form-input,
        .form-textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #E5E5EA;
            border-radius: 10px;
            font-size: 14px;
            font-family: inherit;
            transition: all 0.3s;
            background: white;
        }

        .form-input:focus,
        .form-textarea:focus {
            outline: none;
            border-color: #007AFF;
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }

        .form-textarea {
            min-height: 120px;
            resize: vertical;
            line-height: 1.6;
        }

        .form-hint {
            font-size: 12px;
            color: #8E8E93;
            margin-top: 6px;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            margin-top: 32px;
            padding-top: 24px;
            border-top: 1px solid #E5E5EA;
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 16px 24px;
            border-radius: 10px;
            color: white;
            font-weight: 500;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            z-index: 1000;
            transform: translateX(400px);
            transition: transform 0.3s;
        }

        .toast.show {
            transform: translateX(0);
        }

        .toast.success {
            background: #34C759;
        }

        .toast.error {
            background: #FF3B30;
        }

        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 20px;
            }

            .header-right {
                width: 100%;
                justify-content: flex-end;
            }

            .form-container {
                padding: 24px;
            }

            .form-actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="toast <?= $messageType ?>" id="toast" style="<?= $message ? '' : 'display: none;' ?>"><?= $message ?></div>

    <div class="container">
        <div class="header">
            <div class="header-left">
                <h1>🔗 价值链内容管理</h1>
                <p>管理价值链下载页面的内容和信息</p>
            </div>
            <div class="header-right">
                <span class="admin-badge">👤 <?= htmlspecialchars($_SESSION['admin_username']) ?></span>
                <a href="index.php" class="btn btn-secondary">← 返回首页</a>
                <a href="index.php?logout=1" class="btn btn-danger">🚪 登出</a>
            </div>
        </div>

        <div class="form-container">
            <div class="form-title">
                <span>📝</span>
                <span><?= $content ? '编辑' : '创建' ?>价值链内容</span>
            </div>

            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

                <div class="form-group">
                    <label class="form-label required">页面标题</label>
                    <input
                        type="text"
                        name="page_title"
                        class="form-input"
                        placeholder="例如：ORBIAI工作室价值链资源"
                        value="<?= htmlspecialchars($content['page_title'] ?? '') ?>"
                        required
                    >
                    <div class="form-hint">显示在下载页顶部的标题</div>
                </div>

                <div class="form-group">
                    <label class="form-label">页面描述</label>
                    <textarea
                        name="page_description"
                        class="form-textarea"
                        placeholder="介绍这个价值链的用途、优势等内容..."
                    ><?= htmlspecialchars($content['page_description'] ?? '') ?></textarea>
                    <div class="form-hint">显示在标题下方的详细说明</div>
                </div>

                <div class="form-group">
                    <label class="form-label required">文件名称</label>
                    <input
                        type="text"
                        name="file_name"
                        class="form-input"
                        placeholder="例如：ORBIAI_ValueChain_v1.0.zip"
                        value="<?= htmlspecialchars($content['file_name'] ?? '') ?>"
                        required
                    >
                    <div class="form-hint">要下载的文件名称</div>
                </div>

                <div class="form-group">
                    <label class="form-label">文件说明</label>
                    <textarea
                        name="file_description"
                        class="form-textarea"
                        placeholder="详细描述文件包含的内容、使用方法、更新日志等..."
                    ><?= htmlspecialchars($content['file_description'] ?? '') ?></textarea>
                    <div class="form-hint">详细描述文件的具体内容和用途</div>
                </div>

                <div class="form-group">
                    <label class="form-label">关联文件</label>
                    <select name="file_id" class="form-input">
                        <option value="">-- 选择要下载的文件 --</option>
                        <?php
                        $allFiles = $db->getAllFiles();
                        foreach ($allFiles as $file):
                            $selected = ($content['file_id'] ?? '') == $file['id'] ? 'selected' : '';
                            $fileSize = formatFileSize($file['file_size']);
                        ?>
                            <option value="<?= $file['id'] ?>" <?= $selected ?>>
                                <?= htmlspecialchars($file['original_name']) ?> (<?= $fileSize ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-hint">选择用户点击下载按钮时要下载的文件</div>
                </div>

                <div class="form-group">
                    <label class="form-label">文件大小</label>
                    <input
                        type="text"
                        name="file_size"
                        class="form-input"
                        placeholder="例如：150MB 或 1.2GB"
                        value="<?= htmlspecialchars($content['file_size'] ?? '') ?>"
                    >
                    <div class="form-hint">显示给用户的文件大小（可自定义，不一定与实际文件一致）</div>
                </div>

                <script>
                function formatFileSize(bytes) {
                    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
                    bytes = Math.max(bytes, 0);
                    const pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
                    const formatted = bytes / Math.pow(1024, pow);
                    return Math.round(formatted * 100) / 100 + ' ' + units[Math.min(pow, units.length - 1)];
                }

                // 当选择文件时，自动填充文件信息
                document.querySelector('select[name="file_id"]').addEventListener('change', function() {
                    const selectedOption = this.options[this.selectedIndex];
                    const fileInfo = selectedOption.textContent;
                    const match = fileInfo.match(/\((.*)\)$/);
                    if (match && !document.querySelector('input[name="file_size"]').value) {
                        document.querySelector('input[name="file_size"]').value = match[1];
                    }
                });
                </script>

                <div class="form-actions">
                    <button type="submit" class="btn" style="flex: 1;">
                        <span>💾</span>
                        <span>保存内容</span>
                    </button>
                    <a href="value_chain.php" class="btn btn-secondary" target="_blank" style="flex: 1; justify-content: center;">
                        <span>👁️</span>
                        <span>预览页面</span>
                    </a>
                </div>
            </form>
        </div>
    </div>

    <?php if ($message): ?>
        <script>
            document.getElementById('toast').classList.add('show');
            setTimeout(() => {
                document.getElementById('toast').classList.remove('show');
            }, 3000);
        </script>
    <?php endif; ?>
</body>
</html>
